package net.bwie.realtime.jtp.dim.sink;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * @Author: FuHe
 * @Date: 2025/6/2
 */
public class DimHbaseSinkFunction extends RichSinkFunction<String> {
    // 定义变量：数据库连接
    private Connection connection = null;

    @Override
    public void open(Configuration parameters) throws Exception {
        // 1 创建配置对象，设置属性值，比如连接zk集群信息
        org.apache.hadoop.conf.Configuration conf = HBaseConfiguration.create();
        conf.set(HConstants.CLIENT_ZOOKEEPER_QUORUM, "node101,node102,node103");
        conf.set(HConstants.CLIENT_ZOOKEEPER_CLIENT_PORT, "2181");
        // 2 实例化Connection连接
        connection = ConnectionFactory.createConnection(conf);
    }

    @Override
    public void invoke(String value, Context context) throws Exception {
        JSONObject jsonObject = JSON.parseObject(value);
        String tableName = jsonObject.getString("hbase_table_name");
        String familyName = jsonObject.getString("family_name");
        String rowKeyColumn = jsonObject.getString("row_key_column");
        String operateType = jsonObject.getString("operate_type");
        JSONObject dataObject = jsonObject.getJSONObject("operate_data");
        // 3 创建表  如果表不存在时创建
        createHbaseTable(tableName, familyName);
        // 4 实例化table对象
        Table table = connection.getTable(TableName.valueOf(tableName));
        // 5-1 插入数据
        if ("insert".equals(operateType) || "update".equals(operateType)) {
            // 依据表的主键字段名称获取对应值
            String rowKeyValue = dataObject.getString(rowKeyColumn);
            Put put = new Put(Bytes.toBytes(rowKeyValue));
            // 添加列
            for (String s : dataObject.keySet()) {
                String string = dataObject.getString(s);
                // 当列值不为null时，插入hbase表
                if (string != null) {
                    put.addColumn(
                            Bytes.toBytes(familyName), Bytes.toBytes(s), Bytes.toBytes(string)
                    );
                }
            }
            table.put(put);
        }
        // 5-2 删除数据
        else if ("delete".equals(operateType)) {
            // 依据表的主键字段获取对应值
            String rowKeyValue = dataObject.getString(rowKeyColumn);
            Delete delete = new Delete(Bytes.toBytes(rowKeyValue));
            table.delete(delete);
        } else {
            System.out.println("数据异常，非insert、updata和delete类型操作，操作数据：" + value);
        }
        // 6 关闭
        table.close();
    }

    private void createHbaseTable(String table, String family) throws IOException {
        // 1 管理对象
        Admin admin = connection.getAdmin();
        // 2 表不存在时，创建表
        TableName tableName = TableName.valueOf(table);
        if (!admin.tableExists(tableName)) {
            // 表描述符  构造器
            TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableName);
            // 列簇描述符  构造器
            ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(family));
            // 表添加列簇
            tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptorBuilder.build());
            // 创建表
            admin.createTable(tableDescriptorBuilder.build());
        }
        admin.close();
    }

    @Override
    public void close() throws Exception {
        super.close();
    }
}






